from django.http import HttpResponse
from django.shortcuts import render

from myapp1.models import Book


# Create your views here.
def home(request):
    """
    处理主页请求的视图函数
    参数:
        request: HTTP请求对象，包含客户端请求信息

    返回值:
        HttpResponse对象，返回"Hello, Django 5!"字符串响应
    """
    # return render(request, 'home.html') # 渲染模板并返回响应
    return HttpResponse("Hello, Django 5!")


# 读书信息列表
def book_list(request):
    # all() ---- 查询所有, 返回QuerySet对象,相当于SQL语句：SELECT * FROM book;
    book_list = Book.objects.all() # 查询所有图书
    print("book_list:",book_list)
    return render(request, 'book_list.html', {'book_list': book_list})



def book_discount_view(request):
    try:
        book = Book.objects.get(title="Python Django5") # 获取图书对象
        discounted_price = book.discount(10) # 调用模型方法，返回打折后的价格
        return HttpResponse(f"打折后的价格: {discounted_price}")
    except Book.DoesNotExist:
        return HttpResponse("未找到指定的书籍")
